import Vue from 'vue'
import Component from 'vue-class-component'
import {readFile, uploadImages} from '@/utils/uploadImage/index'
import './productStyle.css'
import {Toast, Indicator} from 'mint-ui'
import Platform from '@/supports/platform'

@Component
export default class ProductAddClass extends Vue {
  selected = '0'

  productBySelf = {}
  productSelfDesc = ''
  productForm = {}
  productFormDesc = ''
  // 自己创建

  isLoadCover = false
  isLoadFormCover = false
  isLoadImages = false
  isLoadFomrImages = false

  isGetDetail = false
  type = ''
  isCover = false

  created() {
    this.selected = this.$store.getters.productAddType
    if (!this.selected) {
      this.selected = '0'
    }

    this.wrapperHeight = document.documentElement.clientHeight - 112
    this.initProduct()

    eventBus.$on('productAddLoadImage', this.handleProductImageCallBack)
  }

  mounted () {
    this.initProduct()
  }

  initProduct() {
    this.productBySelf = {
      productName: '',
      productBrand: '',
      productCode: '',
      imagesFiles: [],
      cover: '',
      skus: [],
      productDesc: ''
    }

    this.productForm = {
      productName: '',
      productBrand: '',
      productCode: '',
      imagesFiles: [],
      productCover: '',
      newSkus: []
    }

    if (this.$store.getters.productBySelf.imagesFiles && this.$store.getters.productBySelf.imagesFiles.length >= 0) {
      this.productBySelf = this.$store.getters.productBySelf
    }
    // if (this.$store.getters.productByForm) {
    //   this.productByForm = this.$store.getters.productByForm
    // }
  }

  updated () {
    if (this.$route.query.temp && this.$route.query.temp.name && this.$route.query.temp.name === 'productAdd' && !this.isGetDetail) {
      this.isGetDetail = true
      this.getDetail(this.$route.query.temp.product.productId)
      this.$route.query.temp = ''
    } else if (this.$route.query.temp) {
      this.productBySelf.productBrand = this.$route.query.temp
    }
  }

  async getDetail (productId) {
    try {
      const response = await this.$axios.post('/api/v1/product/' + productId)
      if (response.status === 0) {
        this.productForm = response.data
        this.productForm['code'] = ''
        if (this.productForm.skus) {
          let sku = this.productForm.skus[0]
          if (sku.xsizes) {
            let size = sku.xsizes[0]
            console.log('skuImages')
            console.log(size.skuImages)

            this.productForm['imagesFiles'] = []
            for (var i = 0; i < size.skuImages.length; i++) {
              let img = size.skuImages[i]
              if (img && img.length > 0) {
                this.productForm.imagesFiles.push(img)
              }
            }

            let desc = size.skuDesc

            // for (var i = 0; i < size.skuDesc.length; i++) {
            //   if (i === 0) {
            //     desc = size.skuDesc[0]
            //   } else {
            //     desc = desc + ',' + size.skuDesc[i]
            //   }
            // }

            if (desc.length === 1) {
              this.productFormDesc = desc[0]
              this.productFormDesc = desc[0].replace(/<br\s*\/?>/g, '\n')
            } else if (desc.length > 1) {
              this.productFormDesc = desc.join('\n')
            }
            this.productForm['newSkus'] = []
            for (let obj of sku.xsizes) {
              let dic = {showPrice: obj.rmbSettlePrice, size: obj.size, quantity: 1, description: desc}
              this.productForm.newSkus.push(dic)
            }
          }
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  destroyed () {
    this.$store.commit('setProductBySelf', this.productBySelf)
  }

  handlePop () {
    this.$store.commit('setProductAddType', 0)
    this.productBySelf = {}
    this.$router.go(-1)
  }

  beforeRouteLeave(to, from, next) {
        // 设置下一个路由的 meta

  }

  async addRequest () {
    try {
      let params = {}
      if (this.selected === '0') {
        // 自己创建
        if (this.productBySelf.productCode && this.productBySelf.productCode.length > 6) {
          Toast('编码大于6位')
          return
        }
        if (!this.productBySelf.cover || this.productBySelf.cover.length <= 0) {
          Toast('没有封面图')
          return
        }
        if (!this.productBySelf.productBrand) {
          Toast('请输入品牌')
          return
        }
        if (this.productBySelf.productName.length <= 0) {
          Toast('请输入商品名')
          return
        }
        if (this.productBySelf.imagesFiles.length <= 0) {
          Toast('没有商品图片')
          return
        }
        if (this.productBySelf.skus.length <= 0) {
          Toast('没有SKU')
          return
        }
        if (!this.handleCheckSizeNull(this.productBySelf.skus)) {
          Toast('SKU输入不能为空')
          return
        }
        if (!this.handleCheckSize(this.productBySelf.skus)) {
          return
        }
        let descs = this.productBySelf.productDesc.split(/[\n]/g)
        params = {
          code: this.productBySelf.productCode.length > 6 ? this.productBySelf.productCode.substring(0, 6) : this.productBySelf.productCode,
          productCover: this.productBySelf.cover,
          description: descs,
          designerName: this.productBySelf.productBrand.name,
          imageUrls: this.productBySelf.imagesFiles,
          productName: this.productBySelf.productName,
          skus: [{xsizes: this.productBySelf.skus}],
          sourceType: this.selected
        }
      } else {
        // 平台商品
        if (this.productForm.code.length > 6 || this.productForm.code.length <= 0) {
          if (this.productForm.code.length <= 0) {
            Toast('请输入编码')
            return
          }
          Toast('编码大于6位')
          return
        }
        if (!this.productForm.productCover) {
          Toast('没有封面图')
          return
        }
        if (!this.productForm.designerName) {
          Toast('请输入品牌')
          return
        }
        if (!this.productForm.productName) {
          Toast('请输入商品名')
          return
        }
        if (this.productForm.imagesFiles.length <= 0) {
          Toast('没有商品图片')
          return
        }
        if (this.productForm.newSkus.length <= 0) {
          Toast('没有SKU')
          return
        }
        if (!this.handleCheckSizeNull(this.productForm.newSkus)) {
          Toast('SKU输入不能为空')
          return
        }
        if (!this.handleCheckSize(this.productForm.newSkus)) {
          return
        }

        console.log('descs', this.productFormDesc)
        let descs = this.productFormDesc.split(/[\n]/g)
        params = {
          code: this.productForm.code,
          productCover: this.productForm.productCover,
          description: descs,
          designerName: this.productForm.designerName,
          imageUrls: this.productForm.imagesFiles,
          productName: this.productForm.productName,
          skus: [{xsizes: this.productForm.newSkus}],
          sourceType: this.selected
        }
      }
      Indicator.open()

      const response = await this.$axios.post('/buyer/v1/product/add', params)
      if (response.status === 0) {
        // this.filterItems = response.data
        // for (let obj of this.filterItems) {
        //   if (obj.name === '品牌') {
        //     this.$store.commit('setAllBrands', obj.children)
        //   }
        // }
        Toast('新增成功')
        let self = this
        eventBus.$emit('productAdd', 'update')
        setTimeout(function() {
          self.handlePop()
        }, 1000)
      } else {
        Toast('新增失败')
      }
      Indicator.close()
    } catch (e) {
      Indicator.close()

      console.log(e)
    }
  }

  get caculateHeight() {
    return 'height:' + String(this.wrapperHeight) + 'px'
  }

  // 删除SKU
  handlerDeleteSku (index) {
    this.productBySelf.skus.splice(index, 1)
  }

  handleDeleteFormSku (index) {
    this.productForm.newSkus.splice(index, 1)
    this.strongUpdate()
  }

  handlerAddSku () {
    this.productBySelf.skus.push({showPrice: '', size: '', quantity: '', description: [this.productBySelf.productDesc]})
  }

  handlerAddFormSku () {
    this.productForm.newSkus.push({showPrice: '', size: '', quantity: '', description: [this.productFormDesc]})
    this.strongUpdate()
  }

  // 输入的size是否存在
  handleCheckSize (sizes) {
    for (var i = 0; i < sizes.length - 1; i++) {
      let dic1 = sizes[i]
      for (var j = i + 1; j < sizes.length; j++) {
        let dic2 = sizes[j]
        if (dic1.size === dic2.size) {
          Toast('尺码有重复')
          return false
        }
      }
    }
    return true
  }

  handleCheckSizeNull (sizes) {
    for (var i = 0; i < sizes.length; i++) {
      let dic = sizes[i]
      for (let key in dic) {
        if (!dic[key] || dic[key].length <= 0) {
          return false
        }
      }
    }

    return true
  }

  handleFiles(e) {
    this.type = e.target.id
    if (this.type === 'coverFileElem' || this.type === 'formCoverElem') {
      Platform.choosePhotos('1', 'productAddLoadImage')
    } else {
      Platform.choosePhotos('2', 'productAddLoadImage')
    }
  }

  handleProductImageCallBack(images) {
    let imagesArr = images

    if (this.type === 'fileElem') {
      this.productBySelf.imagesFiles = this.productBySelf.imagesFiles.concat(imagesArr)
      if (this.productBySelf.imagesFiles.length > 9) {
        this.productBySelf.imagesFiles = this.productBySelf.imagesFiles.slice(0, 9)
      }
    } else if (this.type === 'coverFileElem') {
      this.productBySelf.cover = imagesArr[0]
    } else if (this.type === 'formImagesFile') {
      this.productForm.imagesFiles = this.productForm.imagesFiles.concat(imagesArr)
      if (this.productForm.imagesFiles.length > 9) {
        this.productForm.imagesFiles = this.productForm.imagesFiles.slice(0, 9)
      }
      this.strongUpdate()
    } else if (this.type === 'formCoverElem') {
      this.productForm.productCover = imagesArr[0]
      this.strongUpdate()
    }
  }

  handleLoadImages() {
    Platform.choosePhotos('2')
  }

  handleDeleteImage (index) {
    this.productBySelf.imagesFiles.splice(index, 1)
  }
  handleDeleteCoverImage (index) {
    this.productBySelf.cover = ''
  }

  handleDeleteFormImage (index) {
    this.productForm.imagesFiles.splice(index, 1)
    let cover = this.productForm.productCover
    this.productForm.productCover = ''
    this.productForm.productCover = cover
  }
  handleDeleteFormCoverImage () {
    this.productForm.productCover = ''
  }

  strongUpdate() {
    let cover = this.productForm.productCover
    this.productForm.productCover = ''
    this.productForm.productCover = cover
  }

  handleJumpToBrand() {
    Indicator.open()
    let self = this
    setTimeout(function() {
      self.$router.push({name: 'brandSelect'})
      setTimeout(function() {
        Indicator.close()
      }, 2000)
    }, 100)
  }

  createImageItem() {
    if (!this.productBySelf.imagesFiles) {
      return
    }
    const item = this.productBySelf.imagesFiles.map((image, index) => {
      return <span>
      <dd class='productDeleteImageClass' onClick={() => this.handleDeleteImage(index)}><icon name='imageDeleteIcon' scale='2'/></dd>
      <img src={image}/>
      </span>
    })
    return item
  }

  createFormImageItem() {
    if (!this.productForm.imagesFiles || this.productForm.imagesFiles.length <= 0) {
      return
    }
    const item = this.productForm.imagesFiles.map((image, index) => {
      return <span>
      <font class='productDeleteImageClass' onClick={() => this.handleDeleteFormImage(index)}><icon name='imageDeleteIcon' scale='2'/></font>
      <img src={image + '?x-oss-process=image/resize,m_pad,h_100,w_100,color_ffffff/quality,Q_80/format,jpg'}/>
      </span>
    })
    return item
  }

  // 自己创建商品
  createCustomProduct () {
    return <div>
      <div class="productAddInput">
        <ul>
          <li class="productAddImage">
            <span>图片</span>
            <div id="fileList" class="productAddImageList">
              {this.createImageItem()}
              <font id="fileElem" onClick={this.handleFiles} v-show={this.productBySelf.imagesFiles && this.productBySelf.imagesFiles.length < 9}>
                <icon id="fileElem" name="addIcon" scale='3'/>
              </font>
            </div>
          </li>
          <li class="productAddImage">
            <span>封面</span>
            <div id="fileList" class="productAddImageList">
              <span v-show = {this.productBySelf.cover && this.productBySelf.cover.length > 0}>
                <dd class='productDeleteImageClass' onClick={this.handleDeleteCoverImage}><icon name='imageDeleteIcon' scale='2'/></dd>
                <img src={this.productBySelf.cover + '?x-oss-process=image/resize,m_pad,h_100,w_100,color_ffffff/quality,Q_80/format,jpg'}/>
              </span>
              <font id="coverFileElem" onClick={this.handleFiles} v-show={!this.productBySelf.cover || this.productBySelf.cover.length === 0 }>
                <icon id="coverFileElem" name="addIcon" scale='3'/>
              </font>
            </div>
          </li>
          <li>
            <span>名称</span>
            <input type="text" placeholder="请输入名称" v-model={this.productBySelf.productName}/>
          </li>
          <li onClick={this.handleJumpToBrand}>
            <span>品牌</span>
            <input type="text" placeholder="请选择品牌" value={this.productBySelf.productBrand ? this.productBySelf.productBrand.name : ''} disabled="disabled"/>
            <icon name="rightArrow" class="rightArrow" scale='1.2'/>
          </li>
          <li>
            <span>编码</span>
            <input type="text" placeholder="(1～6位字母加数字)" v-model={this.productBySelf.productCode}/>
          </li>
          <li>
            <span>描述</span>
            <textarea placeholder="输入商品描述" v-model={this.productBySelf.productDesc}></textarea>
          </li>
        </ul>
      </div>
      {/* <mt-field class='addImageLine' label="名称" placeholder="请输入名称" v-model={this.productBySelf.productName}></mt-field> */}
      {/* <mt-cell class = 'addImageLine' title='品牌' value={this.productBySelf.productBrand ? this.productBySelf.productBrand.name : ''} to='brandSelect' is-link></mt-cell> */}
      {/* <mt-field class='addImageLine' label="编码" placeholder="(1～6位字母加数字)" v-model={this.productBySelf.productCode}></mt-field> */}

      {/* <mt-field class ='addImageLine' label="描述" placeholder="输入商品描述" v-model={this.productSelfDesc} type="textarea" rows="4" ></mt-field> */}
      <div class='productFromSkuList'>
        <table cellspacing='0'>
          <thead>
            <tr>
              <td width='40'>SKU</td>
              <td>价格</td>
              <td>尺码</td>
              <td>库存</td>
              <td width='40'><span onClick={this.handlerAddSku}><icon name='addIcon' scale='2.5'/></span></td>
            </tr>
          </thead>
          <tbody>
            {this.createSkuTable()}
          </tbody>
        </table>
      </div>
      {/* <div class='productFromSkuListClass'>
        <h1>SKU</h1>
        <p>价格</p>
        <p>尺码</p>
        <p>库存</p>
        <span onClick={this.handlerAddSku}><icon style='width:10%;float:right;margin-top:8px' name='addIcon' scale='2.5'/></span>
      </div>
      <table class='skuFormTableClass' cellpadding="0" cellspacing="0" >
        {this.createSkuTable()}
      </table> */}
    </div>
  }

  createSkuTable() {
    if (!this.productBySelf.skus) {
      return
    }
    const item = this.productBySelf.skus.map((value, index) => {
      return <tr>
          <td width='40'>
            {index + 1}
          </td>
          <td>
            <input type="text" placeholder="￥" v-model={value.showPrice}/>
          </td>
          <td>
            <input type="text" placeholder="尺码" v-model= {value.size}/>
          </td>
          <td>
            <input type="text" placeholder="库存" v-model={value.quantity}/>
          </td>
          <td width='40' onClick={() => this.handlerDeleteSku(index)}>
            <icon name='deleteIcon' scale='2'/>
          </td>
        </tr>
    })
    return item
  }

  createFromSkuTable() {
    if (!this.productForm.newSkus || this.productForm.newSkus.length <= 0) {
      return
    }
    const item = this.productForm.newSkus.map((value, index) => {
      return <tr>
          <td width='40'>
            {index + 1}
          </td>
          <td >
            <input type="text" placeholder="价格" v-model={value.showPrice}/>
          </td>
          <td>
            <input type="text" placeholder="尺码" v-model={value.size}/>
          </td>
          <td>
            <input type="text" placeholder="库存" v-model={value.quantity}/>
          </td>
          <td width='40' onClick={() => this.handleDeleteFormSku(index)}>
            <icon name='deleteIcon' scale='2'/>
          </td>
        </tr>
    })
    return item
  }

  // 平台商品
  createPlatProduct () {
    return <div>
      <div class="productAddInput">
        <ul>
          <li onClick={() => { this.$router.push({name: 'productCopy'}) }}>
            <span>商品</span>
            <input type="text" placeholder="请选择商品" value={this.productForm.productName ? this.productForm.productName : ''} disabled="disabled"/>
            <icon name="rightArrow" class="rightArrow" scale='1.2'/>
          </li>

          <li class="productAddImage">
            <span>图片</span>
            <div id="fileList" class="productAddImageList">
              {this.createFormImageItem()}
              <font id="formImagesFile" onClick={this.handleFiles} v-show={!this.productForm.imagesFiles || this.productForm.imagesFiles.length < 9}>
                <icon id="formImagesFile" name="addIcon" scale='3'/>
              </font>
            </div>
          </li>
          <li class="productAddImage">
            <span>封面</span>
            <div id="fileList" class="productAddImageList">
              <span v-show={this.productForm.productCover && this.productForm.productCover.length > 0}>
                <dd class='productDeleteImageClass' onClick={this.handleDeleteFormCoverImage}><icon name='imageDeleteIcon' scale='2'/></dd>
                <img src={this.productForm.productCover + '?x-oss-process=image/resize,m_pad,h_100,w_100,color_ffffff/quality,Q_80/format,jpg'}/>
              </span>
              <font id="formCoverElem" onClick={this.handleFiles} v-show={!this.productForm.productCover || this.productForm.productCover.length === 0 }>
                <icon id="formCoverElem" name="addIcon" scale='3'/>
              </font>
            </div>
          </li>
          <li>
            <span>品牌</span>
            <input type="text" placeholder="请输入品牌" v-model={this.productForm.designerName}/>
          </li>
          <li>
            <span>编码</span>
            <input type="text" placeholder="(1～6位字母加数字)" v-model={this.productForm.code}/>
          </li>
          <li>
            <span>描述</span>
            <textarea placeholder="输入商品描述" v-model={this.productFormDesc}></textarea>
          </li>
        </ul>
      </div>
      <div class='productFromSkuList'>
        <table cellspacing='0'>
          <thead>
          <tr>
            <td width='40'>SKU</td>
            <td>价格</td>
            <td>尺码</td>
            <td>库存</td>
            <td width='40'><span onClick={this.handlerAddFormSku}><icon name='addIcon' scale='2.5'/></span></td>
          </tr>
          </thead>
          <tbody>
          {this.createFromSkuTable()}
          </tbody>
        </table>
      </div>
    </div>
  }

  handleType (value) {
    if (this.selected === '0') {
      this.selected = '1'
    } else {
      this.selected = '0'
    }
    this.$store.commit('setProductAddType', this.selected)
  }

  render () {
    return (
      <div class='content'>
        <mt-header class='header' fixed title="增加商品">
        <mt-button onClick={this.handlePop} icon="" slot="left"><icon name = 'backIcon' scale='2'/></mt-button>
        <mt-button onClick={this.addRequest} icon="" slot="right"><icon name = 'completeIcon' scale='2'/></mt-button>
        </mt-header>

        <mt-navbar style='margin-top:64px' value={this.selected} onInput={value => this.handleType(value)}>
          <mt-tab-item id="0">自己创建</mt-tab-item>
          <mt-tab-item id="1">从平台复制</mt-tab-item>
        </mt-navbar>

        <mt-tab-container style={this.caculateHeight + ';overflow:auto; background:#fff'} v-model={this.selected}>
          <mt-tab-container-item id="0">
            {this.createCustomProduct()}
          </mt-tab-container-item>
          <mt-tab-container-item id="1">
            {this.createPlatProduct()}
          </mt-tab-container-item>
        </mt-tab-container>
      </div>
    )
  }
}
